package com.learn.project.aop;

import com.learn.project.annotation.DataSourceSelector;
import com.learn.project.config.DbContextHolder;
import com.learn.project.enums.DBTypeEnum;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author lijiajun
 * @date 2023/11/21
 */
@Aspect
@Component
public class DataSourceAop {

    /**
     * 切面
     */
    @Pointcut("@annotation(com.learn.project.annotation.DataSourceSelector)")
    public void dataSourcePointcut() {
    }

    @Around("dataSourcePointcut()&&@annotation(dataSourceSelector)")
    public Object execute(ProceedingJoinPoint pjp, DataSourceSelector dataSourceSelector) throws Throwable {
        try {
            if (dataSourceSelector.value().equals(DBTypeEnum.Master)) {
                DbContextHolder.master();
            } else if (dataSourceSelector.value().equals(DBTypeEnum.Slave)) {
                DbContextHolder.slave();
            } else {
                throw new RuntimeException("DataSourceSelector value error");
            }
            return pjp.proceed();
        } finally {
            DbContextHolder.clear();
        }
    }
}
